package com.cch.android.activity.view;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

import com.cch.android.activity.ModelLandscapActivity;
import com.cch.android.activity.R;
import com.cch.android.util.Constant;
import com.cch.android.util.MyLog;

public class VirtualActivity extends Activity implements OnSeekBarChangeListener,OnClickListener{
	
	private FrameLayout view_lay;
	  
    private ImageView mImageView;
    
    private Button effect_close,effect_save;
    /**
     * 虚化图片
     */
    private Bitmap mBitmap; 
    
	/**
	 * 变化后的图片
	 */
	private Bitmap bmpSet;
	
    /**
	 * 所选择图片位置
	 */
	private int mIndex;
	
	/**
	 * 本地图片路径集合
	 */
	private ArrayList<String> pathes;
	/**
	 * 虚化坐标
	 */
	private float xVir = 0;

	private float yVir = 0;
	/**
	 * 圆移动坐标
	 */
	private float x = 0;

	private float y = 0;
	/**
	 * 虚化的半径
	 */
	private float r = Constant.m_screenWidth/4;
	
	
	 /** 
     * SeekBar的中间值 
     */  
    private static final int MIDDLE_VALUE = Constant.m_screenWidth/4;  
      
    /** 
     * SeekBar的最大值 
     */  
    private static final int MAX_VALUE = Constant.m_screenWidth/2; 
    
    /**
     * 半径标识
     */
    private static final int RADIUS =0x0; 
    
    private SeekBar rBar; 
    
    private Button virBtn;
    
    private Boolean flag;
	/**
	 * 画出一个圆
	 */
	private View myView;
	private Paint mPaint ;
	  @Override
	   public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.model_setimage_virtual);
		Intent intent = getIntent();
		
		mBitmap = intent.getParcelableExtra("imageBmp");
		initView();
		initRound();
		
		
	}
	  /**
	   * 初始化数据
	   */
	  private void initView(){
		     rBar  = (SeekBar) findViewById(R.id.edit_view_1_virtual_seekbar);
		     virBtn = (Button) findViewById(R.id.edit_view_1_virtual_btn);
		     effect_close = (Button) findViewById(R.id.setimage1_virtual_colse);
		     effect_save= (Button) findViewById(R.id.setimage1_virtual_save);
		     mImageView = (ImageView) findViewById(R.id.setimage1_virtual_image);
		     virBtn.setOnClickListener(this);
		     effect_close.setOnClickListener(this);
		     effect_save.setOnClickListener(this);
		     rBar.setMax(MAX_VALUE); 
		     rBar.setProgress(MIDDLE_VALUE);
		     rBar.setOnSeekBarChangeListener(this);
		     rBar.setTag(0);  
	      
	        if(mBitmap!=null)
	        mImageView.setImageBitmap(mBitmap);
	  }
	  @Override
	protected void onDestroy() {
		  if (mBitmap != null) {
				mBitmap.recycle();
				System.gc();
				mBitmap=null;
			}
			if (bmpSet != null) {
				bmpSet.recycle();
				System.gc();
				bmpSet=null;
			}
		super.onDestroy();
		
	}
	/**
	   * 画圆
	   */
	  private void initRound(){
		  
		  view_lay = ((FrameLayout) findViewById(R.id.setimage1_theimage_lay));
		  
		  x = Constant.m_screenWidth/2;

	      y = Constant.m_screenHeight/2;
	      
		  myView = new MyView(this);
		  view_lay.addView(myView);
		  myView.setOnTouchListener(new OnTouchListener() {

	        	@Override
	        	public boolean onTouch(View v, MotionEvent event) {
	        	// TODO Auto-generated method stub
	        	flag = true;
	        	// 当控件被点中时，flag设为true
	        	//不能写在onClick事件中
	        	return false;
	        	}

	        	});
		  
	  };
	  public boolean onTouchEvent(MotionEvent event) {
			System.out.println("移动的坐标：x:"+x+",y"+y);

			x = event.getX();
			
			xVir = x;

			y = event.getY();

			switch (event.getAction()) {

			case MotionEvent.ACTION_DOWN:
				if(myView.getVisibility()==View.GONE)myView.setVisibility(View.VISIBLE);
//				myView.invalidate();
				

				break;
				
			case MotionEvent.ACTION_UP:

				flag = false;

				break;
	
			case MotionEvent.ACTION_MOVE:
				if (flag) {
					MyLog.log("x:" + x);
					int bmHeight = getSetBitmap().getHeight();
	
					if (y >= (Constant.m_screenHeight - bmHeight) / 2
							&& y <= (Constant.m_screenHeight + bmHeight) / 2) {
						myView.invalidate();
					}
				}
				break;
	
			}

			return super.onTouchEvent(event);

		}
	  /** 
	     * 光晕效果 
	     * @param bmp 
	     * @param x 光晕中心点在bmp中的x坐标 
	     * @param y 光晕中心点在bmp中的y坐标 
	     * @param r 光晕的半径 
	     * @return 
	     */  
	    public Bitmap halo(Bitmap bmp, float x, float y, float r)  
	    {  
	    	
	    	System.out.println("虚化的坐标：x:"+x+",y"+y);
	        long start = System.currentTimeMillis();  
	        // 高斯矩阵  
	        int[] gauss = new int[] { 1, 2, 1, 2, 4, 2, 1, 2, 1 };  
	          
	        int width = bmp.getWidth();  
	        int height = bmp.getHeight();  
	        y = y-(Constant.m_screenHeight-height)/2;
	        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);  
	          
	        int pixR = 0;  
	        int pixG = 0;  
	        int pixB = 0;  
	          
	        int pixColor = 0;  
	          
	        int newR = 0;  
	        int newG = 0;  
	        int newB = 0;  
	          
	        int delta = 22; // 值越小图片会越亮，越大则越暗  
	          
	        int idx = 0;  
	        int[] pixels = new int[width * height];  
	        bmp.getPixels(pixels, 0, width, 0, 0, width, height);  
	        for (int i = 1, length = height - 1; i < length; i++)  
	        {  
	            for (int k = 1, len = width - 1; k < len; k++)  
	            {  
	                idx = 0;  
	                int distance = (int) (Math.pow(k - x, 2) + Math.pow(i - y, 2));  
	                // 不是中心区域的点做模糊处理  
	                if (distance > r * r)  
	                {  
	                    for (int m = -1; m <= 1; m++)  
	                    {  
	                        for (int n = -1; n <= 1; n++)  
	                        {  
	                            pixColor = pixels[(i + m) * width + k + n];  
	                            pixR = Color.red(pixColor);  
	                            pixG = Color.green(pixColor);  
	                            pixB = Color.blue(pixColor);  
	                              
	                            newR = newR + (int) (pixR * gauss[idx]);  
	                            newG = newG + (int) (pixG * gauss[idx]);  
	                            newB = newB + (int) (pixB * gauss[idx]);  
	                            idx++;  
	                        }  
	                    }  
	                      
	                    newR /= delta;  
	                    newG /= delta;  
	                    newB /= delta;  
	                      
	                    newR = Math.min(255, Math.max(0, newR));  
	                    newG = Math.min(255, Math.max(0, newG));  
	                    newB = Math.min(255, Math.max(0, newB));  
	                      
	                    pixels[i * width + k] = Color.argb(255, newR, newG, newB);  
	                      
	                    newR = 0;  
	                    newG = 0;  
	                    newB = 0;  
	                }  
	            }  
	        }  
	          
	        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);  
	        long end = System.currentTimeMillis();  
	        return bitmap;  
	    }  
	    class MyView extends View{
			

			public MyView(Context context) {
				super(context);
				mPaint = new Paint();
				mPaint.setStyle(Style.STROKE);
				mPaint.setColor(Color.WHITE);
				mPaint.setAntiAlias(true);
			}
			@Override
			protected void onDraw(Canvas canvas) {

			canvas.drawCircle(x, y, r, mPaint);

			super.onDraw(canvas); 

			}
		}
		@Override
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			  int flag = (Integer) seekBar.getTag();  
		        switch (flag)  
		        {  
		        case RADIUS:  
		        	MyLog.log("虚化半径："+progress);
		        	r= progress;
		        	myView.invalidate();
		            break;  
		        }
		}
			
		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
			// TODO Auto-generated method stub
			
		}
		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			// TODO Auto-generated method stub
			
		}
		@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.edit_view_1_virtual_btn:
			Bitmap bmp = null;
			if (mBitmap != null) {
				
				bmp = halo(mBitmap, x, y, r);
				if (bmp != null){
					mImageView.setImageBitmap(bmp);
					myView.setVisibility(View.GONE);
				}
			}
			break;
		case R.id.setimage1_virtual_colse:
//			backToMain();
			finish();
			break;
		case R.id.setimage1_virtual_save:
			saveToMain();
			break;
		}
		}
		private void backToMain(){
			Intent intent = new Intent();
			intent.putExtra("imageBmp", mBitmap);
			intent.setClass(this, ModelLandscapActivity.class);
			startActivity(intent);
		}
		/**
		 * 保存到sd卡 回到美化图片主界面
		 */
		private void saveToMain(){
			Intent intent = new Intent();
			intent.putExtra("imageBmp", getSetBitmap());
			intent.setClass(this, ModelLandscapActivity.class);
			startActivity(intent);
		}
		/**
		 * 得到处理的图片
		 * @return
		 */
		private Bitmap getSetBitmap(){
			if (mImageView != null) {
				if (bmpSet != null) {
					bmpSet.recycle();
					System.gc();
					bmpSet=null;
				}
				bmpSet = Constant.drawable2Bitmap(mImageView.getDrawable());
				return bmpSet;
			}
			return bmpSet;
		}
}
